// 碳资产统计分析展示
import React, { Children, useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import './assetAnalysis.less';
import { Table, Button, Input } from 'antd';
import 'antd/dist/antd.css';
import { getAnnualInformation, getAnalysisList } from '@/services/carbon'

const assetAnalysis = (props) => {
  // 头部数据值
  const [annualInformation, setgetAnnualInformation] = useState({})
  // 表格总数据
  const [dataSource, setDataSource] = useState([]);
  // 分页数据
  const [pagination, setPagination] = useState({
    pageNum: 1,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 项目查询值
  const [itemName, setItemName] = useState('');
  // 类型查询值
  const [itemType, setItemType] = useState('');
  // 业主查询值
  const [ownerName, setOwnerName] = useState('');
  // 表格自适应高度
  const [scrollY, setScrollY] = useState(0);
  const containerRef = useRef(null);
  // 表格自适应高度钩子
  useEffect(() => {
    const handleResize = () => {
      if (containerRef.current) {
        const containerHeight = containerRef.current.clientHeight;
        setScrollY(containerHeight - 230); // 100 是你想减去的像素值
      }
    };
    handleResize(); // 初始化时计算高度
    window.addEventListener('resize', handleResize); // 添加 resize 事件监听
    return () => {
      window.removeEventListener('resize', handleResize); // 清理事件监听
    };
  }, []);

  useEffect(() => {
    // 调用获取图表接口
    fetchAnnualInformationsData()
    // 调用表格数据接口
    fetchAnalysisList()
  }, [])

  // 监听当前页发生改变，查询表格数据
  useEffect(() => {
    fetchAnalysisList();
  }, [pagination.pageNum])

  // 切换当前页，修改当前页的值，再触发监听钩子
  const handlePaginationChange = (page) => {
    setPagination({ ...pagination, pageNum: page, current: page });
  };

  // 获取表格数据接口
  const fetchAnalysisList = async (params) => {
    try {
      // 拼接页数数据及筛选项数据，获取接口数据并赋值
      const res = await getAnalysisList({ ...pagination, itemName: itemName, ownerName: ownerName, itemType: itemType })
      if (res.code === 200) {
        setDataSource(res)
        setPagination({ ...pagination, total: res.total })
      }
    } catch (error) {
      console.error(error);
    }
  };

  const fetchAnnualInformationsData = async () => {
    try {
      // 获取接口数据并赋值
      const res = await getAnnualInformation()
      if (res.code === 200) {
        setgetAnnualInformation(res.data)
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 表格列配置
  const columns = [
    { title: '项目名称', dataIndex: 'itemName', key: 'itemName', width: '55%', align: 'center' },
    { title: '资金投入', dataIndex: 'money', key: 'money', width: "15%", align: 'center' },
    { title: '项目类型', dataIndex: 'itemType', key: 'itemType', width: "15%", align: 'center' },
    { title: '预估降碳量(万吨CO2)', dataIndex: 'emissionReductionNum', key: 'emissionReductionNum', width: "15%", align: 'center' },
  ];

  // 处理搜索按钮点击事件
  const handleSearch = () => {
    if (pagination.pageNum === 1) {
      fetchAnalysisList()
    } else {
      setPagination({ ...pagination, pageNum: 1, current: 1 });
    }
  };

  return (
    <div className="assetAnalysis-content">
      <div className="top-box">
        <div className="left-box">
          <div className="count-box">
            <div className="title">年度降碳目标</div>
            <div className="counts-box">
              <span className="count">{annualInformation.carbonReductionTargets}</span>
              <span className="unit">万吨co2</span>
            </div>
          </div>
        </div>
        <div className="right-box">
          <div className="count-box">
            <div className="title">年度累计降碳量</div>
            <div className="counts-box">
              <span className="count">{annualInformation.accumulatedCarbonReduction}</span>
              <span className="unit">万吨co2</span>
            </div>
          </div>
        </div>
      </div>
      <div className="center-box">
        <div className="filter-container">
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">项目查询:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查询的项目名称"
                value={itemName}
                onChange={e => setItemName(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <span className="filter-name">类型查询:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查询的项目类型名称"
                value={itemType}
                onChange={e => setItemType(e.target.value)}
              />
            </div>
          </div>
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">业主查询:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查找的业主名称"
                value={ownerName}
                onChange={e => setOwnerName(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <Button type="primary" onClick={handleSearch} className="searchBtn">
                搜索
              </Button>
            </div>
          </div>
        </div>

        <div className="table-container" ref={containerRef}>
          <Table
            dataSource={dataSource.rows}
            columns={columns}
            pagination={{
              ...pagination,
              showSizeChanger: false,
              pageSizeOptions: [],
              onChange: handlePaginationChange,
            }}
            scroll={{ y: scrollY }}
          />
        </div>
      </div>
    </div>
  )
};

export default connect()(assetAnalysis);
